<template>
	<view>
		<view class="search-bar">
			<view class="btn-left" :style="{'background-color': primaryColor}" @click="onCancel">
				<span class="iconfont icon-close"></span>
			</view>
			<input class="search-input" type='text' v-model="keyWord" @input="onMapSearch" placeholder="定位不准？试试手动输入" />
			<view class="btn-right" :style="{'background-color': primaryColor}" @click="onConfirm">
				<span class="iconfont icon-checkbox"></span>
				确定
			</view>
		</view>
		<view class="map-container">
			<view id="select-station-pos-map" class="baidu-map"></view>
		</view>
		<view class="content">
			<view class="poi-list">
				<poi-item v-for="(item, index) in mapSeartResults" :key="index" :poi="item" :primaryColor="primaryColor" @selected="onPoiItemClick(item)"></poi-item>
			</view>
		</view>
	</view>
</template>

<script>
	// import {wgs84togcj02, gcj02tobd09, bd09togcj02} from 'coordtransform'
	import poiItem from './poi-item.vue'
	export default {
		components: {
			poiItem
		},
		props: {
			primaryColor: {
				type: String,
				default: () => {
					return '#068888'
				}
			},
			// 默认中心点
			defaultPt: {
				type: [String, Object],
				default: () => {
					return {
						lng: '',
						lat: ''
					}
				}
			},
			// 默认的地址
			defaultAddress: {
				type: String,
				default: () => {
					return ''
				}
			}
		},
		watch: {
			defaultPt: {
				immediate: true,
				handler(newVal, val) {
					if (newVal && newVal.lng && newVal.lat) {
						console.log('defaultPt changed', newVal, val)
						this.centerPoint = newVal
						this.needGetCurrentLocation = false
					}
				}
			}
		},
		data() {
			return {
				keyWord: "",

				needGetCurrentLocation: true,
				zoomLevel: 15,
				centerPoint: {
					lng: 113.95918,
					lat: 22.56864
				},

				mapSeartResults: [],
				mapObj: null,
				geoCoder: '',
				currentSelectedPoi: ''
			}
		},
		computed: {
			activeAddressColor() {
				return {
					color: this.primaryColor
				}
			}
		},
		created() {},
		onLoad(option) {
			console.log('pos selector', option)
			let lng = option.lng
			let lat = option.lat
			if (lng && lat) {
				this.centerPoint = {
					lng: parseFloat(lng),
					lat: parseFloat(lat)
				}
				this.needGetCurrentLocation = false
			}
		},
		methods: {
			getCurrentLocation() {
				console.log('getCurrentLocation')
				let that = this

				return new Promise((resolve, reject) => {
					if (process.env.NODE_ENV == 'development') {
						resolve()
						return
					}

					uni.getLocation({
						type: 'gcj02',
						success(res) {
							console.log('weixin-js-sdk wx.getLocation success', res)
							// let [lng, lat] = gcj02tobd09(res.longitude, res.latitude)
							let [lng, lat] = [res.longitude, res.latitude]
							that.centerPoint = {
								lng,
								lat
							}
							uni.showToast({
								icon: 'none',
								title: '定位到当前位置.'
							})
							resolve()
						},
						fail(res) {
							console.log('weixin-js-sdk wx.getLocation fail', res)
							uni.showToast({
								icon: 'none',
								title: '定位失败，无法获取附近电站' + JSON.stringify(res)
							})
							reject()
						}
					})
				})
			},
			onCancel() {
				console.log('onCancel')
				this.$emit('cancel')
			},
			onConfirm() {
				console.log('onConfirm', JSON.stringify(this.currentSelectedPoi))
				this.$emit('confirm', this.currentSelectedPoi)
			},
			onPoiItemClick(item) {
				console.log('onPoiItemClick', item)
				if (this.currentSelectedPoi) {
					this.currentSelectedPoi.selected = false
				}
				// this.$set(item, 'selected', true)
				item.selected = true
				this.currentSelectedPoi = item
				this.markOnMap(item)
			},
			onMapSearch() {
				console.log("onMapSearch", this.keyWord);
				if (this.mapSearch) {
					this.mapSearch.search(this.keyWord);
				}
			},
			searchSurroundingPois(pt) {
				if (!this.geoCoder) return
				var mOption = {
					//半径为1000米内的POI,默认100米
					poiRadius: 500,
					//列举出50个POI,默认10个
					numPois: 12
				}
				this.geoCoder.getLocation(pt, (res) => {
					console.log('geoCoder.getLocation', res)
					this.mapSeartResults = res.surroundingPois.map(item => {
						item.selected = false
						return item
					})
				}, mOption)
			},
			initMap() {
				console.log("onMapSelectDlgOpened", this.centerPoint);
				if (this.mapObj == null) {
					this.mapObj = new BMapGL.Map("select-station-pos-map");
				}
				let pt = new BMapGL.Point(this.centerPoint.lng, this.centerPoint.lat);
				this.mapObj.centerAndZoom(pt, this.zoomLevel);
				this.mapObj.addControl(
					new BMapGL.MapTypeControl({
						mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP]
					})
				);
				this.mapObj.enableScrollWheelZoom(true);

				this.geoCoder = new BMapGL.Geocoder({
					extensions_town: true
				});
				this.mapObj.addEventListener("click", e => {
					console.log('mapObject click', e)
					//如果是点击的marker，则不需要响应
					if (e.overlay) return
					var pt = e.latlng;
					this.geoCoder.getLocation(pt, rs => {
						console.log("on map click", rs);
						var addComp = rs.addressComponents;
						if (rs.surroundingPois.length) {
							rs.title = rs.surroundingPois[0].title
						}
						this.currentSelectedPoi = rs
						this.markOnMap(rs, false);
						this.searchSurroundingPois(rs.point)
					});
				});

				var options = {
					onSearchComplete: results => {
						// 判断状态是否正确
						console.log("onSearchComplete", results);
						if (this.mapSearch.getStatus() == BMAP_STATUS_SUCCESS) {
							var resultList = [];
							for (var i = 0; i < results.getCurrentNumPois(); i++) {
								console.log(results.getPoi(i));
								resultList.push(results.getPoi(i));
							}
							this.mapSeartResults = resultList;
						}
					}
				};
				this.mapSearch = new BMapGL.LocalSearch(this.mapObj, options);

				this.$nextTick(() => {
					this.markOnMap({
						point: this.centerPoint,
						address: this.defaultAddress
					});
				});
				this.searchSurroundingPois(pt)
			},
			markOnMap(poi, moveToCenter = true) {
				console.log('markOnMap', poi)
				this.centerPoint = {
					lat: poi.point.lat,
					lng: poi.point.lng
				};
				var point = new BMapGL.Point(poi.point.lng, poi.point.lat);
				var marker = new BMapGL.Marker(point); // 创建标注
				this.mapObj.clearOverlays();

				this.mapObj.addOverlay(marker); // 将标注添加到地图中
				if (moveToCenter) {
					// this.mapObj.centerAndZoom(point, this.zoomLevel);
					this.mapObj.panTo(point);
				}
				let title = poi.title ? poi.title : "";
				var opts = {
					width: 160,
					height: 40,
					title: title
				};
				var infoWindow = new BMapGL.InfoWindow(poi.address, opts); // 创建信息窗口对象

				marker.addEventListener("click", (event) => {
					this.mapObj.openInfoWindow(infoWindow, point); //开启信息窗口
				});
				this.$nextTick(() => {
					if (poi.address) this.mapObj.openInfoWindow(infoWindow, point); //开启信息窗口
				})
			},
		},
		mounted() {
			console.log('map selector mounted', this.needGetCurrentLocation)
			if (this.needGetCurrentLocation) {
				this.getCurrentLocation().finally(() => {
					this.initMap()
				})
				return
			}
			this.initMap()
		},
	}
</script>

<style scoped lang="scss">
	@import "./iconfont.css";
	// https://zhuanlan.zhihu.com/p/339222388
	// 隐藏页面顶部返回按钮的方法
	$uni-font-size-sm:24rpx;
	$uni-font-size-base:28rpx;
	$uni-font-size-lg:32rpx;
	$hj-margin-h: 32rpx;
	$hj-padding-h: 32rpx;
	$hj-padding-v: 32rpx;
	$hj-font-color-title: #313131;
	$hj-font-color-subtitle: rgba(49, 49, 49, 0.7);

	.hj-normal-text {
		font-size: $uni-font-size-base;
		color: $hj-font-color-title;
	}

	.hj-subtitle {
		font-size: $uni-font-size-sm;
		color: $hj-font-color-subtitle;
	}

	.search-bar {
		display: flex;
		// margin: $hj-padding-v 0;
		// width: 750rpx;
		justify-content: space-between;
		padding: $hj-padding-v/2 $hj-padding-h;

		.search-input {
			// width: 350rpx;
			flex-grow: 2;
			height: 60rpx;
			margin: 0 $hj-padding-h;
			border-radius: 30rpx;
			background: rgba(0, 0, 0, .06);
			padding: 5rpx 24rpx;
			font-size: 24rpx;
		}

		.btn-left {
			display: flex;
			justify-content: space-between;
			align-items: center;
			// width: 120rpx;
			// background-color: #068888;
			color: white;
			border-radius: 10rpx;
			padding: 0rpx 14rpx;
			// margin-right: $hj-padding-h;
		}

		.btn-right {
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100rpx;
			// background-color: #068888;
			color: white;
			border-radius: 10rpx;
			padding: 0rpx 14rpx;
			// margin-left: $hj-padding-h;
		}
	}

	.map-container {
		.baidu-map {
			width: 100%;
			height: 500rpx;
		}
	}

	.content {
		margin: $hj-padding-v $hj-padding-h/2;

		.poi-list {
			margin: $hj-padding-v $hj-padding-h/2;

			.poi {
				padding-bottom: $hj-padding-v/2;
				margin: $hj-padding-v/2 0;
				border-bottom: 0.5rpx solid #D3D3D3;
				display: flex;
				justify-content: space-between;

				.right {
					display: flex;
					justify-content: center;
					align-items: center;
				}

			}
		}
	}
</style>
